package com.ruoyi.system.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.Brand;
import com.ruoyi.system.domain.Cate;
import com.ruoyi.system.domain.Spec;
import com.ruoyi.system.domain.imp.TypeImport;
import com.ruoyi.system.domain.vo.TypeVO;
import com.ruoyi.system.domain.vo.Type_mini;
import com.ruoyi.system.mapper.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.Type;
import com.ruoyi.system.service.ITypeService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 分类管理Service业务层处理
 *
 * @author ruoyi
 * @date 2024-08-30
 */
@Service
public class TypeServiceImpl implements ITypeService {
    @Resource
    private TypeMapper typeMapper;
    @Resource
    private CateMapper cateMapper;
    @Resource
    private SpecMapper specMapper;
    @Resource
    private BrandMapper brandMapper;
    @Autowired
    private ComputeMapper computeMapper;

    /**
     * 查询分类管理
     *
     * @param id 分类管理主键
     * @return 分类管理
     */
    @Override
    public Type selectTypeById(Long id) {
        Type type = typeMapper.selectTypeById(id);
        Map<Long, Type> typeMap = typeMapper.selectTypeList(new Type()).stream().collect(Collectors.toMap(Type::getId, t -> t));
        Map<Long, Cate> cateMap = cateMapper.selectCateList(new Cate()).stream().collect(Collectors.toMap(Cate::getId, t -> t));
        Map<Long, Spec> specMap = specMapper.selectSpecList(new Spec()).stream().collect(Collectors.toMap(Spec::getId, t -> t));
        Map<Long, Brand> brandMap = brandMapper.selectBrandList(new Brand()).stream().collect(Collectors.toMap(Brand::getId, t -> t));
        formatType(type, typeMap, cateMap, specMap, brandMap);
        return type;
    }

    /**
     * 查询分类管理列表
     *
     * @param type 分类管理
     * @return 分类管理
     */
    @Override
    public List<Type> selectTypeList(Type type) {
        List<Type> types = typeMapper.selectTypeList(type);

        Map<Long, Type> typeMap = typeMapper.selectTypeList(new Type()).stream().collect(Collectors.toMap(Type::getId, t -> t));
        Map<Long, Cate> cateMap = cateMapper.selectCateList(new Cate()).stream().collect(Collectors.toMap(Cate::getId, t -> t));
        Map<Long, Spec> specMap = specMapper.selectSpecList(new Spec()).stream().collect(Collectors.toMap(Spec::getId, t -> t));
        Map<Long, Brand> brandMap = brandMapper.selectBrandList(new Brand()).stream().collect(Collectors.toMap(Brand::getId, t -> t));

        types.forEach(item -> {
            formatType(item, typeMap, cateMap, specMap, brandMap);
        });
        return types;
    }

    @Override
    public List<Type_mini> selectTypeList_mini(Type type) {
        List<Type> types = typeMapper.selectTypeList(type);
        List<Type_mini> type_minis = new ArrayList<>(10);
        types.forEach(item -> {
            type_minis.add(new Type_mini(item.getId(), item.getName()));
        });
        return type_minis;
    }

    private void formatType(Type type, Map<Long, Type> typeMap, Map<Long, Cate> cateMap, Map<Long, Spec> specMap, Map<Long, Brand> brandMap) {
        if (type.getParentId().equals(0L)) {
            type.setParentName("/");
        } else {
            if (typeMap.containsKey(type.getParentId())) {
                Type type_parent = typeMap.get(type.getParentId());
                if (type_parent != null) {
                    type.setParentName(type_parent.getName());
                }
            }
        }

        if (type.getCateId() != null) {
            if (cateMap.containsKey(type.getCateId())) {
                Cate cate = cateMap.get(type.getCateId());
                if (cate != null) {
                    type.setCateName(cate.getName());
                }
            }

        }

        if (type.getSpecId() != null) {
            if (specMap.containsKey(type.getSpecId())) {
                Spec spec = specMap.get(type.getSpecId());
                if (spec != null) {
                    type.setSpecName(spec.getName());
                }
            }

        }

        if (type.getBrandId() != null) {
            if (brandMap.containsKey(type.getBrandId())) {
                Brand brand = brandMap.get(type.getBrandId());
                if (brand != null) {
                    type.setBrandName(brand.getName());
                }
            }

        }
    }

    /**
     * 新增分类管理
     *
     * @param type 分类管理
     * @return 结果
     */
    @Override
    public int insertType(Type type) {
        type.setCreateTime(DateUtils.getNowDate());
        return typeMapper.insertType(type);
    }

    /**
     * 修改分类管理
     *
     * @param type 分类管理
     * @return 结果
     */
    @Override
    public int updateType(Type type) {
        type.setUpdateTime(DateUtils.getNowDate());
        return typeMapper.updateType(type);
    }

    /**
     * 批量删除分类管理
     *
     * @param ids 需要删除的分类管理主键
     * @return 结果
     */
    @Override
    public int deleteTypeByIds(Long[] ids) {
        return typeMapper.deleteTypeByIds(ids);
    }

    /**
     * 删除分类管理信息
     *
     * @param id 分类管理主键
     * @return 结果
     */
    @Override
    public int deleteTypeById(Long id) {
        return typeMapper.deleteTypeById(id);
    }

    /**
     * 导入分类
     */
    @Override
    @Transactional
    public void importType(List<TypeImport> list) {
        Map<String, Spec> specMap = specMapper.selectSpecList(new Spec()).stream().collect(Collectors.toMap(Spec::getName, t -> t));
        Map<String, Brand> brandMap = brandMapper.selectBrandList(new Brand()).stream().collect(Collectors.toMap(Brand::getName, t -> t));


        Map<String, List<TypeImport>> collect = list.stream().collect(Collectors.groupingBy(TypeImport::getCateName));

        List<TypeImport> errorList = new ArrayList<>(10);
        List<Type> typeList = new ArrayList<>(10);
        Date date = new Date();
        collect.forEach((key, value) -> {
            List<Cate> cateS = cateMapper.selectCateList(new Cate() {{
                setName(key);
            }});
            Cate cate = null;
            if (cateS != null && !cateS.isEmpty()) {
                cate = cateS.get(0);

            } else {
                cate = new Cate(key);
                cate.setCreateTime(date);
                cateMapper.insertCate(cate);
            }
            List<TypeImport> typeImports = collect.get(key);
            for (TypeImport item_in : typeImports) {
                Spec spec = null;
                Brand brand = null;
                String typeName = item_in.getTypeName();
                String specName = item_in.getSpecName();
                String brandName = item_in.getBrandName();
                if (specMap.containsKey(specName)) {
                    spec = specMap.get(specName);
                } else {
                    spec = new Spec(specName);
                    spec.setCreateTime(date);
                    specMapper.insertSpec(spec);
                    specMap.put(specName, spec);
                }
                if (brandMap.containsKey(brandName)) {
                    brand = brandMap.get(brandName);
                } else {
                    brand = new Brand(brandName);
                    brand.setCreateTime(date);
                    brandMapper.insertBrand(brand);
                    brandMap.put(brandName, brand);
                }
                Type type = new Type(cate.getId(), typeName, spec.getId(), brand.getId());
                List<Type> types = typeMapper.selectTypeList(type);
                if (types != null && !types.isEmpty()) {
                    errorList.add(item_in);
                } else {
                    type.setCreateTime(date);
                    typeList.add(type);
                }
            }

        });
        if (!errorList.isEmpty()) {
            StringBuilder errMsg = new StringBuilder();
            errorList.forEach(item -> {
                errMsg.append(item.getCateName()).append("-").append(item.getTypeName()).append("-").append(item.getSpecName()).append("-").append(item.getBrandName()).append("已存在\n");
            });
            throw new ServiceException(errMsg.toString());
        }

        if (!typeList.isEmpty()) {
            typeMapper.insertTypeBatch(new HashMap<String, Object>() {{
                put("typeList", typeList);
            }});
        }

    }
}
